<template>
	<view class="wrap">
		<u-form class="form" :model="model" :rules="rules" ref="uForm" :label-position="labelPosition">
			<u-form-item label="直播主题" prop="theme" label-width="180" :required="true">
				<u-input v-model="model.theme" type="text" placeholder="请输入直播主题" maxlength="64" style="text-align: left;" :disabled="disabled"></u-input>
			</u-form-item>
			<u-form-item label="发起者" prop="anchorName" label-width="180" :required="true">
				<u-input v-model="model.anchorName" :type="disabled?'input':'select'" placeholder="请选择发起者" :disabled="disabled" @click="chooseAnchor"></u-input>
				<js-choose-user-popup v-if="useInitChooseUserComp" ref="chooseAnchor" @submit="useAnchorSelected"
					:mode="popupAdmin.mode" :multiple="popupAdmin.multiple"
					:action="chooseUserUrl" :default-selected-user-list = "defaultAnchorUserList"></js-choose-user-popup>
			</u-form-item>
			<u-form-item label="开始时间" prop="startTime" label-width="180" :required="true">
				<view style="width: 100%;">
					<u-input v-model="model.startTime == ''?'请选择开始时间':model.startTime" :type="disabled?'input':'select'" @click="uPickerStartTime.show = !disabled" :disabled="disabled"></u-input>
					<u-picker v-model="uPickerStartTime.show" :mode="uPickerStartTime.mode" :params="uPickerStartTime.params" @confirm="confirm4StartTime"></u-picker>
				</view>
			</u-form-item>
			<u-form-item v-if="!showEndTime" label="持续时长" prop="duration" label-width="180" :required="true">
				<js-select v-model="duration" dict-type="wechat_living_duration" itemLabel="dictValue"
					itemValue="dictKey" placeholder="请选择持续时长" :disabled="disabled" @input="durationChange"></js-select>
			</u-form-item>
			<u-form-item v-if="showEndTime" ref="uFormItemEndTime" label="结束时间" prop="endTime" label-width="180" :required="true">
				<view style="width: 100%;">
					<u-input v-model="model.endTime == ''?'请选择结束时间':model.endTime" :type="disabled?'input':'select'" @click="uPickerEndTime.show = !disabled" :disabled="disabled"></u-input>
					<u-picker v-model="uPickerEndTime.show" :mode="uPickerEndTime.mode" :params="uPickerEndTime.params" @confirm="confirm4EndTime"></u-picker>
				</view>
			</u-form-item>
			<u-form-item label="直播类型" prop="liveType" label-width="180" :required="true">
				<js-select v-model="model.liveType" dict-type="wechat_liveType" itemLabel="dictValue"
					itemValue="dictKey" placeholder="请选择直播类型" :disabled="disabled"></js-select>
			</u-form-item>
			<u-form-item label="提醒时间" prop="remindTime" label-width="180">
				<js-select v-model="model.remindTime" dict-type="wechat_remind_before" itemLabel="dictValue"
					itemValue="dictKey" placeholder="请选择提醒时间" :disabled="disabled"></js-select>
			</u-form-item>
			<u-form-item label="直播简介" prop="description" label-width="180" label-position="top">
				<u-input v-model="model.description" type="textarea" placeholder="请输入直播简介" height="100" maxlength="500" :disabled="disabled"/>
			</u-form-item>
			<u-form-item label="活动简介" prop="adDescription" label-width="180" label-position="top">
				<u-input v-model="model.adDescription" type="textarea" placeholder="请输入活动简介" height="100" maxlength="500" :disabled="disabled"/>
			</u-form-item>
			<u-form-item label="封面图(大小10M以下)" prop="activityCover" label-width="180" label-position="top">
				<text slot="labelCustomExtension">{{ currentSelectedActivityCoverFileCount }}/{{ upload.maxCountActivityCover }}</text>
				<wechat-upload ref="activityCoverUpload" :form-data="{type:'image'}" :file-list="activityCoverFileList" upload-text="选择图片" accept="image" :extension="upload.imageExt" :max-count="upload.maxCountActivityCover" :max-size="upload.maxSizeActivityCover" :deletable="upload.deletable" :select-file-able="upload.selectFileAble" @on-list-change="onActivityCoverFileListChangeCallBack"></wechat-upload>
			</u-form-item>
			<u-form-item label="分享卡片图(大小5M以下)" prop="activityShare" label-width="180" label-position="top">
				<text slot="labelCustomExtension">{{ currentSelectedActivityShareFileCount }}/{{ upload.maxCountActivityShare }}</text>
				<wechat-upload ref="activityShareUpload" :form-data="{type:'image'}" :file-list="activityShareFileList" upload-text="选择图片" accept="image" :extension="upload.imageExt" :max-count="upload.maxCountActivityShare" :max-size="upload.maxSizeActivityShare" :deletable="upload.deletable" :select-file-able="upload.selectFileAble" @on-list-change="onActivityShareFileListChangeCallBack"></wechat-upload>
			</u-form-item>
			<u-form-item label="活动附图(大小10M以下)" prop="adImage" label-width="180" label-position="top">
				<text slot="labelCustomExtension">{{ currentSelectedAdImageFileCount }}/{{ upload.maxCountAdImage }}</text>
				<wechat-upload ref="adImageUpload" :form-data="{type:'image'}" :file-list="adImageFileList" upload-text="选择图片" accept="image" :extension="upload.imageExt" :max-count="upload.maxCountAdImage" :max-size="upload.maxSizeAdImage" :deletable="upload.deletable" :select-file-able="upload.selectFileAble" @on-list-change="onAdImageFileListChangeCallBack"></wechat-upload>
			</u-form-item>
		</u-form>
		<slot name="footerBtns">
			<view style="display: flex;flex-direction: row;">
				<u-button v-if="!isViewMode" class="btn" style="width: 50%;margin-right: 10rpx;" type="primary" @click="submit">保存</u-button>
				<u-button class="btn" style="width: 50%;" @click="cancel">
					{{isViewMode ? '返回' : '取消'}}
				</u-button>
			</view>
		</slot>
	</view>
</template>
<script>
	import WechatUpload from '@/pages/wechat/wechat-upload.vue'
	
	/**
	 * @property {Stringr | Number} id 主键ID
	 * @property {Stringr} modeProp 模式（view、eidit、add）外部传入的属性
	 */
	export default {
		components: {
			WechatUpload
		},
		props: {
			id: {
				type: [String,Number],
				default: ''
			},
			modeProp: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				model: {
					theme: '',
					anchorName: '',
					anchorUserid: '',
					startTime: '',
					endTime: '',
					liveType: '',
					remindTime: '',
					description: '',
					adDescription: '',
					activityCoverMediaid: '',
					activityShareMediaid: '',
					adImageList: ''
				},
				isModelLoadedFlag: false,
				// 操作模式：view、add、edit
				mode: '',
				duration: '',
				uPickerStartTime: {
					show: false,
					mode: 'time',
					params: {
						year: true,
						month: true,
						day: true,
						hour: true,
						minute: true,
						second: true
					},
				},
				uPickerEndTime: {
					show: false,
					mode: 'time',
					params: {
						year: true,
						month: true,
						day: true,
						hour: true,
						minute: true,
						second: true
					},
				},
				isViewMode: false,
				//是否显示结束时间表单项，同时控制持续时长表单项的切换
				showEndTime: false,
				showRepeatType: false,
				labelPosition: 'left',
				disabled: true,
				rules: {
					theme: [{
						required: true,
						message: '请输入直播主题',
						trigger: ['blur','change']
					}],
					startTime: [
						{
							required: true,
							message: '请选择开始时间',
							trigger: 'change'
						},
						{
							validator: (rule, value, callback) => {
								let startTime = new Date(value);
								let curTime = new Date();
								if(startTime.getTime() < curTime.getTime()){
									return false;
								}
								return true;
							},
							message: '开始时间不能小于当前时间',
							trigger: 'change'
						}
					],
					duration: [{
						validator: (rule, value, callback) => {
							// duration不是model对象的属性，所以value没有值
							let validateResult = true;
							let duration = this.duration;
							if(!this.showEndTime && !duration){
								validateResult = false;
							}
							return validateResult;
						},
						message: '请选择持续时长',
						trigger: 'change'
					}],
					endTime: [
						{
							required: true,
							message: '请选择结束时间',
							trigger: 'change',
						},
						{
							validator: (rule, value, callback) => {
								let endTime = new Date(value);
								if(this.model.startTime){
									let startTime = new Date(this.model.startTime);
									if(endTime.getTime() < startTime.getTime()){
										callback(new Error('结束时间不能小于开始时间'));
									}else{
										callback();
									}
								}else{
									callback(new Error('请先选择开始时间'));
								}
							},
							trigger: 'change'
						}
					],
					// 验证规则的type属性默认类型为string，而在详情接口返回中liveType是数值，
					// 发生'liveType is not a string'，从而在编辑页面中提示检验不通过。
					// 解决方法指定type: 'number'，或validator自定义方法。
					liveType: [{
						required: true,
						message: '请选择直播类型',
						type: 'number',
						trigger: 'change'
					}],
					anchorName: [{
						required: true,
						message: '请选择发起者',
						trigger: 'change'
					}]
				},
				labelPosition: 'left',
				chooseUserUrl: '/api/blade-system/user/user-list-by-dept-type',
				popupAdmin: {
					show: false,
					mode: "bottom",
					multiple: false
				},
				dictDataOptions: {
					
				},
				upload: {
					deletable: true,
					selectFileAble: true,
					imageExt: ['.jpg','.png','.jpeg'],
					maxCountActivityCover: 1,
					maxCountActivityShare: 1,
					maxCountAdImage: 5,
					maxSizeActivityCover: 10 * 1024 * 1024,
					maxSizeActivityShare: 5 * 1024 * 1024,
					maxSizeAdImage: 10 * 1024 * 1024
				},
				//已有封面图列表
				activityCoverFileList:[],
				//标识当前已上传的封面图文件数
				currentSelectedActivityCoverFileCount: 0,
				//已有分享卡片图列表
				activityShareFileList:[],
				//标识当前已上传的分享卡片图文件数
				currentSelectedActivityShareFileCount: 0,
				//已有活动附图列表
				adImageFileList:[],
				//标识当前已上传的活动附图文件数
				currentSelectedAdImageFileCount: 0
			};
		},
		computed: {
			/**
			 * 返回是否初始化选择用户组件的标识
			 * 解决父组件将请求回来的数据传递给子组件的延迟问题
			 */
			useInitChooseUserComp: function(){
				let useInit = false;
				if(this.mode === 'add' || (this.mode === 'edit' && this.isModelLoadedFlag)){
					useInit = true;
				}
				return useInit;
			},
			defaultAnchorUserList: function(){
				let userList = [];
				if(this.model.adminUserid){
					userList.push({
						id: this.model.adminUserid,
						name: this.model.adminName
					});
				}
				return userList;
			}
		},
		watch: {
			'model.startTime': function(val,oldVal){
				if(val && this.$refs.uFormItemEndTime && this.mode != 'view'){
					this.$refs.uFormItemEndTime.$emit('on-form-change');
				}
			},
			activityCoverFileList: function(val,oldVal){
				if(val && val.length && val.length > 0){
					this.currentSelectedActivityCoverFileCount = val.length;
				}
			},
			activityShareFileList: function(val,oldVal){
				if(val && val.length && val.length > 0){
					this.currentSelectedActivityShareFileCount = val.length;
				}
			},
			adImageFileList: function(val,oldVal){
				if(val && val.length && val.length > 0){
					this.currentSelectedAdImageFileCount = val.length;
				}
			}
		},
		beforeCreate(){
			
		},
		onLoad(params) {
			// onLoad 监听页面加载，其参数为上个页面传递的数据，参数类型为 Object（用于页面传参）
			// console.log("1.onLoad...");
			this.initData(params);
		},
		created() {
			// console.log("2.created...");
			if(this.id){
				// 场景适用于当前组件在弹出层中的展示
				let params = {
					id: this.id
				};
				if(this.modeProp){
					params.mode = this.modeProp;
				}
				this.initData(params);
			}
		},
		onReady() {
			// console.log("3.onReady...");
			this.$refs.uForm.setRules(this.rules);
		},
		beforeMount(){
			
		},
		mounted(){
			// console.log("4.mounted...");
		},
		methods: {
			initData(params){
				let vm = this;
				this.mode = params.mode;
				if (params.id) {
					this.showEndTime = true;
					if (this.mode == "view") {
						this.disabled = true;
						this.isViewMode = true;
						// 在view模式下文件的上传及删除操作需要禁用；
						this.upload.deletable = false;
						this.upload.selectFileAble = false;
					} else {
						this.disabled = false;
						this.isViewMode = false;
						// 服务端API的修改预约直播，没有提供直播间封面图、直播分享卡片图及活动直播附图的修改；
						// 所以在edit模式下文件的上传及删除操作需要禁用；
						this.upload.deletable = false;
						this.upload.selectFileAble = false;
					}
					this.$u.api.wechat.wechatLiving.detail({
						id: params.id
					}).then(res => {
						Object.assign(vm.model, res.data);
						vm.initFillFiles();
						vm.isModelLoadedFlag = true;
					});
				} else {
					this.disabled = false;
					this.showEndTime = false;
				}
			},
			/**
			 * 初始回填已有的文件数据
			 */
			initFillFiles(){
				if(this.model.activityCoverMediaid){
					let activityCoverMediaid = JSON.parse(this.model.activityCoverMediaid);
					this.activityCoverFileList = activityCoverMediaid.map(item => {
						return {
							url: item.value,
							name: item.label,
							mediaId: item.mediaId
						}
					})
				}
				if(this.model.activityShareMediaid){
					let activityShareMediaid = JSON.parse(this.model.activityShareMediaid);
					this.activityShareFileList = activityShareMediaid.map(item => {
						return {
							url: item.value,
							name: item.label,
							mediaId: item.mediaId
						}
					})
				}
				if(this.model.adImageList){
					let adImageList = JSON.parse(this.model.adImageList);
					this.adImageFileList = adImageList.map(item => {
						return {
							url: item.value,
							name: item.label,
							mediaId: item.mediaId
						}
					})
				}
			},
			durationChange(val){
				if(val == 4){
					this.model.endTime = '';
					this.showEndTime = true;
					//将回调延迟到下次 DOM 更新循环之后执行
					this.$nextTick(() => {
						if(this.$refs.uFormItemEndTime){
							this.$refs.uFormItemEndTime.$emit('on-form-change')
						}
					});
				}
			},
			getPickerResult(e,params){
				let pickerResult = '';
				if (params.year) {
					pickerResult += e.year;
				}
				if (params.month) {
					pickerResult += '-' + e.month;
				}
				if (params.day) {
					pickerResult += '-' + e.day;
				}
				if (params.hour) {
					pickerResult += ' ' + e.hour;
				}
				if (params.minute) {
					pickerResult += ':' + e.minute;
				}
				if (params.second) {
					pickerResult += ':' + e.second;
				}
				return pickerResult;
			},
			confirm4StartTime(e) {
				this.model.startTime = this.getPickerResult(e,this.uPickerStartTime.params);
				this.uPickerStartTime.show = false;
			},
			confirm4EndTime(e) {
				this.model.endTime = this.getPickerResult(e,this.uPickerEndTime.params);
				this.uPickerEndTime.show = false;
			},
			chooseAnchor() {
				if(this.disabled){
					return;
				}
				this.$refs.chooseAnchor.open();
				this.$refs.chooseAnchor.setDefaultSelectedUserList(this.defaultAnchorUserList);
			},
			useAnchorSelected() {
				let anchorArr = this.$refs.chooseAnchor.getData();
				if (anchorArr.length > 0) {
					let anchor = anchorArr[0];
					this.model.anchorUserid = anchor.id;
					this.model.anchorName = anchor.name;
				}
				this.$refs.chooseAnchor.close();
			},
			onActivityCoverFileListChangeCallBack(lists) {
				this.currentSelectedActivityCoverFileCount = lists.length;
			},
			onActivityShareFileListChangeCallBack(lists) {
				this.currentSelectedActivityShareFileCount = lists.length;
			},
			onAdImageFileListChangeCallBack(lists) {
				this.currentSelectedAdImageFileCount = lists.length;
			},
			getActivityCoverFileList() {
				let files = this.$refs.activityCoverUpload.getFileList();
				let fileList = [];
				files.forEach(item => {
					if(item.response && item.response.data){
						//当前新上传的文件
						let data = item.response.data;
						const { mediaId, link, originalName } = data;
						fileList.push({
							label: originalName,
							value: link,
							mediaId: mediaId
						});
					}else{
						//默认已有的文件
						const {name,url} = item;
						let mediaId = '';
						let found = this.activityCoverFileList.find(element => element.url == url);
						if(found){
							mediaId = found.mediaId;
						}
						fileList.push({
							label: name,
							value: url,
							mediaId: mediaId
						});
					}
				})
				return fileList;
			},
			getActivityShareFileList() {
				let files = this.$refs.activityShareUpload.getFileList();
				let fileList = [];
				files.forEach(item => {
					if(item.response){
						//当前新上传的文件
						let data = item.response.data;
						const { mediaId, link, originalName } = data;
						fileList.push({
							label: originalName,
							value: link,
							mediaId: mediaId
						});
					}else{
						//默认已有的文件
						const {name,url} = item;
						let mediaId = '';
						let found = this.activityShareFileList.find(element => element.name == name && element.url == url);
						if(found){
							mediaId = found.mediaId;
						}
						fileList.push({
							label: name,
							value: url,
							mediaId: mediaId
						});
					}
				})
				return fileList;
			},
			getAdImageFileList() {
				let files = this.$refs.adImageUpload.getFileList();
				let fileList = [];
				files.forEach(item => {
					if(item.response){
						//当前新上传的文件
						let data = item.response.data;
						const { mediaId, link, originalName } = data;
						// 注意字段与群消息、应用消息不一样，如：mediaId
						fileList.push({
							label: originalName,
							value: link,
							mediaId: mediaId
						});
					}else{
						//默认已有的文件
						const {name,url} = item;
						let mediaId = '';
						let found = this.adImageFileList.find(element => element.name == name && element.url == url);
						if(found){
							mediaId = found.mediaId;
						}
						// 注意字段与群消息、应用消息不一样，如：mediaId
						fileList.push({
							label: name,
							value: url,
							mediaId: mediaId
						});
					}
				})
				return fileList;
			},
			doBeforeModelPost: function(){
				if(!this.showEndTime){
					//根据持续时长计算结束时间
					let startTime = new Date(this.model.startTime);
					let secondsOfEndTime = startTime.setSeconds(startTime.getSeconds() + parseInt(this.duration));
					this.model.endTime = this.$u.timeFormat(secondsOfEndTime,'yyyy-mm-dd hh:MM:ss');
				}
				let activityCoverFileList = this.getActivityCoverFileList();
				if(activityCoverFileList.length > 0){
					this.model.activityCoverMediaid = JSON.stringify(activityCoverFileList);
				}
				let activityShareFileList = this.getActivityShareFileList();
				if(activityShareFileList.length > 0){
					this.model.activityShareMediaid = JSON.stringify(activityShareFileList);
				}
				let adImageFileList = this.getAdImageFileList();
				if(adImageFileList.length > 0){
					this.model.adImageList = JSON.stringify(adImageFileList);
				}
			},
			submit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						// console.log("submit...");
						uni.showLoading({
							title: '提交中....'
						})
						this.doBeforeModelPost();
						let promise = null;
						if(this.mode == 'edit'){
							promise = this.$u.api.wechat.wechatLiving.edit(this.model)
						}else{
							promise = this.$u.api.wechat.wechatLiving.save(this.model);
						}
						promise.then(res => {
							uni.hideLoading();
							uni.showModal({
								title: '提示',
								content: res.msg,
								showCancel: false,
								success: function() {
									if (res.code == 200) {
										uni.setStorageSync('refreshWecahtLivingList', true);
										uni.navigateBack();
									}
								}
							});
						});
					} else {
						this.$u.toast('您填写的信息有误，请根据提示修正。');
					}
				});
			},
			cancel() {
				uni.navigateBack();
			}
		}
	};
</script>
<style lang="scss" scoped>
	.wrap {
		padding: 30rpx;
	}

	.uTagStyle {
		margin-right: 10rpx;
	}

	.scroll-Y {
		height: 200rpx;
	}

	/deep/ ::-webkit-scrollbar {
		/*滚动条整体样式*/
		width: 4px !important;
		height: 1px !important;
		overflow: auto !important;
		background: #ccc !important;
		-webkit-appearance: auto !important;
		display: block;
	}

	/deep/ ::-webkit-scrollbar-thumb {
		/*滚动条里面小方块*/
		border-radius: 10px !important;
		box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2) !important;
		background: #7b7979 !important;
	}

	/deep/ ::-webkit-scrollbar-track {
		/*滚动条里面轨道*/
		background: #FFFFFF !important;
	}
</style>